import {
  Button,
  Pagination,
  Table,
  PaginationProps as AntPaginationProps,
  Space,
  Splitter,
} from 'antd';
import { memo, useEffect, useRef, useState } from 'react';
import '@/pages/know-gov/styles/know-gov.scss';
import { PaginationProps, PaginationResponse } from '@/common';
import { ColumnsType } from 'antd/es/table';
import { useDebounceFn, useSize } from 'ahooks';
import { CloseOutlined } from '@ant-design/icons';
import { useLocation } from 'react-router-dom';
import NotData from '@/components/NotData';
import Tables from '@/components/tables/tables';
interface SelectOperator<T> {
  name: string;
  onClick: (data: T[]) => Promise<void>;
}

interface Props<TParams extends PaginationProps, TData extends PaginationResponse> {
  searchText?: string;
  api: (data: TParams) => Promise<TData>;
  columns: ColumnsType<any>;
  rowKey?: string;
  refreshKey?: number;
  rowSelection?: {};
  setDataList?: (datas: any[]) => void;
  filtType?: string;
  selectOperators?: SelectOperator<any>[];
  isNeedLoad?: boolean;
}

// 定义一个泛型函数 PaginationTable，用于生成分页表格
const PaginationTable = <TParams extends PaginationProps, TData extends PaginationResponse>({
  api,
  searchText = '',
  columns,
  rowKey,
  refreshKey,
  rowSelection,
  setDataList,
  filtType,
  selectOperators = [],
  isNeedLoad,
}: Props<TParams, TData>) => {
  // 定义分页相关状态
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [datas, setDatas] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  // 定义表格引用和表格大小
  const tableRef = useRef<HTMLDivElement>(null);
  const size = useSize(tableRef);
  const [scroll, setScroll] = useState({ x: 'calc(700px + 50%)', y: 'calc(80vh - 100px)' });
  const [selectedRows, setSelectedRows] = useState<TData[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const appId = queryParams.get('appId') || '';

  // 监听表格大小变化，更新滚动条位置
  useEffect(() => {
    if (tableRef.current && size) {
      setScroll({
        x: 'calc(700px + 50%)',
        y: `${size?.height - 140}px`,
      });
    }
  }, [size]);

  // 定义分页改变事件
  const onChange: AntPaginationProps['onChange'] = (current, pageSize) => {
    setPage(current);
    setPageSize(pageSize);
  };

  // 使用防抖函数，延迟获取数据
  const { run } = useDebounceFn(
    () => {
      getDatas();
    },
    {
      wait: 500,
    },
  );

  // 获取数据函数
  const getDatas = async () => {
    try {
      !isNeedLoad && setLoading(true);
      const res = await api({
        page: page,
        page_size: pageSize,
        searchText: searchText,
        type: filtType,
        app_id: appId,
      } as TParams);
      setDatas(res?.list || []);
      setTotal(res?.total || 0);
      setDataList && setDataList(res?.list || []);
    } catch (error) {
      console.error(error);
    } finally {
      !isNeedLoad && setLoading(false);
    }
  };

  const rowSelectionConfig = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: TData[]) => {
      setSelectedRows(selectedRows);
      setSelectedRowKeys(selectedRowKeys);
    },
    selectedRowKeys: selectedRowKeys,
  };

  const clearSelections = () => {
    setSelectedRows([]);
    setSelectedRowKeys([]);
  };

  const checkPage = () => {
    const newTotalPages = Math.max(Math.ceil(total / pageSize), 1);
    if (page > newTotalPages) {
      setPage(newTotalPages);
    }
  };

  // 监听分页和搜索框变化，获取数据
  useEffect(() => {
    !isNeedLoad && setLoading(true);
    checkPage();
    run();
  }, [page, pageSize, total]);

  // 监听刷新键变化，获取数据
  useEffect(() => {
    !isNeedLoad && setLoading(true);
    clearSelections();
    run();
  }, [refreshKey]);

  // 监听搜索框变化，重置分页，获取数据
  useEffect(() => {
    !isNeedLoad && setLoading(true);
    setPage(1);
    setPageSize(10);
    run();
  }, [searchText, filtType]);

  // 返回分页表格组件
  return (
    <div className="h-full flex-1 rounded-default px-5 text-[#292D32]" ref={tableRef}>
      {datas.length > 0 ? (
        <Tables
          loading={loading}
          rowKey={rowKey || 'keyQuestionId'}
          columns={columns}
          dataSource={datas}
          pagination={false}
          rowClassName="bg-[#F6F7FB]"
          rowSelection={selectOperators.length > 0 ? rowSelectionConfig : rowSelection}
          // scroll={scroll}
          paginationProps={{
            total: total,
            current: page,
            pageSize: pageSize,
            onChange: onChange,
          }}
        />
      ) : (
        <NotData />
      )}

      {/* <Table
        // rowSelection={rowSelection}
        loading={loading}
        rowKey={rowKey || 'keyQuestionId'}
        columns={columns}
        dataSource={datas}
        pagination={false}
        // scroll={scroll}
        rowSelection={selectOperators.length > 0 ? rowSelectionConfig : rowSelection}
        locale={{
          emptyText: <NotData />
        }}
      />
      <div className="mb-4 ml-auto mr-10 mt-auto">
        <Pagination
          defaultCurrent={1}
          total={total}
          pageSize={pageSize}
          current={page}
          showSizeChanger
          onChange={onChange}
        />
      </div> */}
      {selectOperators.length > 0 && selectedRows.length > 0 && (
        <div
          className="animated-div"
          style={{
            position: 'fixed',
            bottom: '5%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#474C5F',
            borderRadius: '50px',
          }}
        >
          <Space className="ml-2 mr-2" style={{ height: '45px' }}>
            <Button
              style={{ color: '#fff' }}
              type="text"
              icon={<CloseOutlined />}
              onClick={clearSelections}
            ></Button>
            <span className="whitespace-nowrap text-nowrap text-xs" style={{ color: '#8E93A4' }}>
              已选 {selectedRows.length} 项
            </span>
            <Splitter />

            {/* <Button style={{ color: '#fff' }} type="text">
              删除
            </Button> */}
            {selectOperators.map((item, index) => {
              return (
                <Button
                  key={index}
                  style={{ color: '#fff' }}
                  type="text"
                  onClick={async () => {
                    await item.onClick(selectedRows);
                    clearSelections();
                  }}
                >
                  {item.name}
                </Button>
              );
            })}
          </Space>
        </div>
      )}
    </div>
  );
};

export default memo(PaginationTable);
